package com.esg.esgproject.mp.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esg.esgproject.mp.entity.auto.News;
import com.esg.esgproject.mp.qo.QoNews;
import com.esg.esgproject.mp.service.NewsService;
import com.esg.esgproject.mp.service.impl.NewsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author z100
 * @since 2021-12-15
 */
@RestController
@RequestMapping("/news")
@Api(tags = "新闻接口")
public class NewsController {

    @Autowired
    NewsService newsService;

    /**
     * 增
     * @param news
     */
    @PutMapping("/add")
    @ApiOperation(value = "添加新闻" ,notes = "传json")
    public ResponseEntity<Object> add(News news){
        newsService.save(news);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     *删
     * @param id /news/1
     */

    @DeleteMapping("/del")
    @ApiOperation("del新闻，通过id")
    public ResponseEntity<Object> delete(@ApiParam("要删的news的id") @RequestParam("id") Long id){
        boolean res = newsService.removeById(id);
        return res?new ResponseEntity<>(HttpStatus.OK):new ResponseEntity<>(HttpStatus.FAILED_DEPENDENCY);
    }

    /**
     * 模糊查询实例，自定义前端需要查询的字段到qo包中的查询类中
     * QoNews字段数<=News
     * @param condition
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("模糊查询")
    public ResponseEntity<Object> search(QoNews condition){
        LambdaQueryWrapper<News> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(News::getTitle,condition.getTitle());
        List<News> list = newsService.list(wrapper);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 查询全部，分页查询的简化版
     * @return
     */
    @GetMapping("/getAll")
    @ApiOperation("获取全部新闻")
    public ResponseEntity<Object> getAll(){
        List<News> all = newsService.list();
        return new ResponseEntity<>(all, HttpStatus.OK);
    }


    /**
     * 更新
     * @param newNews
     * @param oldId
     * @return
     */
    @PutMapping("update")
    @ApiOperation("update新闻")
    public ResponseEntity<Object> update(News newNews,Long oldId){
        LambdaQueryWrapper<News> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(News::getId,oldId);
        boolean update = newsService.update(newNews, wrapper);
        return update?new ResponseEntity<>(HttpStatus.OK):new ResponseEntity<>(HttpStatus.FAILED_DEPENDENCY);


    }



}
